﻿using Plexi.Science;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;

namespace Plexi.Tools
{
	public static class TextureManager
	{
		private const string _rockTextureBasePath = "PLEXI/Textures/Rocks", _iconTexturePath = "PLEXI/Textures/PlexiIcon";
		private static Texture _failTexture;

		/// <summary>Returns a magenta colored fallback texture to be used whenever a texture fails to load. (Lazy init)</summary>
		public static Texture FailTexture
		{
			get
			{
				if (_failTexture == null)
				{
					Texture2D t = new Texture2D(1, 1);
					t.SetPixels32(new Color32[] { XKCDColors.Magenta });
					t.Apply();
					_failTexture = (Texture)t;
				}
				return _failTexture;
			}
		}

		public static Texture[] LoadRockTextures(string rockTypeName)
		{
#if verbose
			Log.Add("Loading rock textures for {0}...", rockTypeName);
#endif
			List<Texture> textures = new List<Texture>();
			Texture tex;
			int i = 0;
			do
			{
				tex = Load(string.Format("{0}/{1}{2}", _rockTextureBasePath, rockTypeName.ToLower(), i++));
				if (tex != null)
					textures.Add(tex);
			} while (tex != null);
			if (textures.Count == 0)
				Log.Add("ERROR: LoadRockTextures: no textures found for rock type {0}.", rockTypeName);
			return textures.ToArray();
		}

		public static Texture LoadToolbarIcon()
		{
			return Load(_iconTexturePath);
		}

		public static Texture Load(string path)
		{
			try
			{
				return (Texture)GameDatabase.Instance.GetTexture(path, false);
			}
			catch (KSP.IO.IOException ex)
			{
				Log.Add("ERROR: TextureManager: failed to load texture from path: {0}", path);
				Log.Add(ex.Message);
			}
			return FailTexture;
		}
	}
}
